<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\BaseHelper;
use app\common\Common;
use app\admin\model\Operator;
use app\admin\model\Productpriceitem;
use app\admin\model\Store;
use app\admin\model\Product;
use app\admin\model\Productcategory;

use think\Db;
use think\Request;

class Productprice extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->defaultOrder = 'create_date DESC';

        if($this->request->action() == 'add' || $this->request->action() == 'edit'){
            // 门店
            $storeList = Store::where(['business_end_time' => ['gt', date('Y-m-d H:i:s')]])->field('id, name')->select();

            $this->assign('storeList', $storeList);
        }
    }

    public function index(){

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        $info['store_ids'] = explode(',', $info['store_ids']);
        // 商品调价的商品明细
        $info['product_ids'] = Productpriceitem::where('product_price_id', $info['id'])->column('product_id');
        $info['product_ids'] = implode(',', $info['product_ids']);
        $info['priceItems'] = Productpriceitem::where('product_price_id', $info['id'])->select();

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    public function savePost(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            Db::startTrans();
            try {
                $data = $request->param();

                if ($data['id']) {
                    // Update data
                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                    $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                    $afterAction = '_after_update';
                } else {
                    // Insert data
                    $data['id'] = BaseHelper::getUUID();
                    $data['order_no'] = BaseHelper::getUUID();
                    $data['create_oper'] = $this->admin->id;
                    $result = $model->save($data);
                    $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                    $afterAction = '_after_insert';
                }

                if($result !== false) {
                    // 商品调价的商品明细
                    if(isset($data['product_id']) && $data['product_id']){
                        // 删除旧的明细
                        Productpriceitem::where('product_price_id', $data['id'])->delete();
                        $newPrice = $data['new_price'];
                        $newWholesaleprice = $data['new_wholesale_price'];
                        //$newMemberintegral = $data['new_member_integral'];
                        foreach ($data['product_id'] as $key => $productId) {
                            $itemData = [
                                'id' => BaseHelper::getUUID(),
                                'product_price_id' => $data['id'],
                                'product_id' => $productId,
                                'new_price' => $newPrice[$key] * 100,
                                'new_wholesale_price' => $newWholesaleprice[$key] * 100,
                                //'new_member_integral' => $newMemberintegral[$key]
                            ];
                            $res = Productpriceitem::insert($itemData);
                            if ($res === false) {
                                Db::rollback();
                                return $this->error('保存调价的商品明细失败');
                            }
                        }
                    }

                    // 生效日期是当天 TODO

                    // Query执行后的操作
                    $model->$afterAction($data);

                    // 写入日志
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index');
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }

        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * Edit
     */
    public function detail(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        // 调价范围
        $info['range'] = $this->formatRange($info['range']);
        // 状态
        if ($info['effective_date'] <= date('Y-m-d')) {
            $info['status'] = '已执行';
        } else {
            $info['status'] = '待执行';
        }

        if($request->isAjax()){
            $model = new Productpriceitem();

            $where = [
                'a.product_price_id' => $id
            ];
            $fields = 'p.img_url, p.name, p.bar_code, p.category_id, p.purchase_price, p.price, p.wholesale_price, p.member_integral, a.new_price, a.new_wholesale_price, a.new_member_integral';
            $order = 'p.create_date DESC';
            $data = $model->alias('a')->where($where)->join('__PRODUCT__ p', 'p.id = a.product_id')->field($fields)->order($order)->select();
            if($data){
                foreach ($data as $item) {
                    // 分类
                    $item['category_id'] = Productcategory::where('id', $item['category_id'])->value('name');
                }
            }
            $count = $model->alias('a')->where($where)->join('__PRODUCT__ p', 'p.id = a.product_id')->count();

            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->fetch('detail', [
            'info' => $info
        ]);
    }

    /**
     * Delete
     */
    public function delete(){
        $request = $this->request;
        $id = $request->param('id');

        $model = model($this->model);
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        Db::startTrans();
        try {
            $result = $model->where('id', $id)->delete();
            if ($result !== false) {
                // 商品价格还原
                $productIds = Productpriceitem::where('product_price_id', $id)->column('product_id');
                $products = Product::where(['id' => ['in', $productIds]])->field('id, old_price, price, old_wholesale_price, wholesale_price, old_member_integral, member_integral')->select();
                foreach ($products as $product) {
                    $productData = [
                        'price' => $product['old_price'],
                        'wholesale_price' => $product['old_wholesale_price'],
                        'member_integral' => $product['old_member_integral']
                    ];
                    $productRes = Product::where('id', $product['id'])->update($productData);
                    if($productRes === false){
                        Db::rollback();
                        return $this->error('回复商品明价格失败！');
                    }
                }
                // 删除调价的商品明细
                $res = Productpriceitem::where('product_price_id', $id)->delete();
                if($res === false){
                    Db::rollback();
                    return $this->error('删除商品明细失败！');
                }

                // Query执行后的操作
                $model->_after_delete($id);

                $logInfo = $this->admin->name . '删除了1条' . lang($this->model) . '数据。';
                Common::adminLog($request, $logInfo);

                Db::commit();
                return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                Db::rollback();
                return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
            }
        } catch (Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            // 调价商品数
            $item['count_product'] = Productpriceitem::where('product_price_id', $item['id'])->count();
            // 调价范围
            $item['range'] = $this->formatRange($item['range']);
            // 状态
            if ($item['effective_date'] <= date('Y-m-d')) {
                $item['status'] = '已执行';
            } else {
                $item['status'] = '待执行';
            }
            // 提交人
            $item['create_oper'] = Operator::where('id', $item['create_oper'])->value('login_name');
        }

        return $data;
    }

    // 调价范围
    protected function formatRange($data){
        // 调价范围
        switch ($data) {
            case 1:
                $data = '商品目录+APP/小程序+所有门店';
                break;
            case 2:
                $data = '商品目录+APP/小程序';
                break;
            case 3:
                $data = '商品目录+所有门店';
                break;
            case 4:
                $data = 'APP/小程序';
                break;
            case 5:
                $data = '指定门店';
                break;
            default: break;
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['order_no']) && $param['order_no']){
            $where['order_no'] = ['like', '%'.$param['order_no'].'%'];
        }

        return $where;
    }

    /**
     * 选择商品
     */
    public function selectProducts(){
        $request = $this->request;
        $param = $request->param();

        if($request->isAjax()){
            $model = new Product();

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            $where = [
                'status' => 1
            ];
            if(isset($param['name']) && $param['name']){
                $where['name'] = ['like', '%'.$param['name'].'%'];
            }
            $fields = 'id, img_url, name, bar_code, category_id, purchase_price, price, wholesale_price, member_integral';
            $order = 'create_date DESC';
            $data = $model->where($where)->field($fields)->order($order)->limit($start, $length)->select();
            if($data){
                foreach ($data as $item) {
                    // 分类
                    $item['category_id'] = Productcategory::where('id', $item['category_id'])->value('name');
                }
            }
            $count = $model->where($where)->count();

            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->view->fetch('productprice/select_products', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * 设置调价
     */
    public function setProductprice(){
        $request = $this->request;
        $param = $request->param();

        if($request->isAjax()){
            $model = new Product();

            $where = [];
            if (isset($param['product_ids']) && $param['product_ids']) {
                $ids = $param['product_ids'];
                $where['id'] = ['in', $ids];
            } else {
                return json([
                    'code' => '0',
                    'msg' => '',
                    'data' => [],
                    'count' => 0,
                ]);
            }
            $fields = 'id, img_url, name, bar_code, category_id, purchase_price, price, wholesale_price';
            $order = 'create_date DESC';
            $data = $model->where($where)->field($fields)->order($order)->select();
            if($data){
                if(isset($param['product_price_id']) && $param['product_price_id']){
                    foreach ($data as $item) {
                        // 商品调价的商品明细
                        $priceItem = Productpriceitem::where(['product_price_id' => $param['product_price_id'], 'product_id' => $item['id']])->find();
                        $item['new_price'] = $priceItem['new_price'] / 100;
                        $item['new_wholesale_price'] = $priceItem['new_wholesale_price'] / 100;
                        $item['new_member_integral'] = $priceItem['new_member_integral'];
                    }
                }
            }
            $count = $model->where($where)->count();

            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->view->fetch('productprice/set_productprice', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }
}